package com.link.play.fit.ai.utils

import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeParseException
import java.time.temporal.ChronoUnit
import java.util.Calendar
import java.util.Locale

object CalendarUtils {
    fun calculateNewEndDate(
        startStr: String,
        endStr: String,
        type: String
    ): String {
        if(startStr.isEmpty() || endStr.isEmpty()) return ""
        val startDate = LocalDate.parse(startStr)
        val endDate = LocalDate.parse(endStr)
        val today = LocalDate.now()

        // 如果结束日期在今天或之后，直接返回原结束日期
        if (!endDate.isBefore(today)) {
            return endStr
        }

        // 根据类型计算新的结束日期
        return when (type.lowercase()) {
            "week" -> calculateWeeklyEndDate(startDate, today)
            "year" -> calculateYearlyEndDate(startDate, today)
            else -> throw IllegalArgumentException("Invalid type. Use 'week' or 'year'.")
        }.format(DateTimeFormatter.ISO_LOCAL_DATE)
    }

    private fun calculateWeeklyEndDate(
        startDate: LocalDate,
        today: LocalDate
    ): LocalDate {
        val daysBetween = ChronoUnit.DAYS.between(startDate, today)
        val totalDays = daysBetween + 1 // 包含今天
        val weeks = ceilDiv(totalDays, 7)
        return startDate.plusDays(weeks * 7 - 1)
    }

    private fun calculateYearlyEndDate(
        startDate: LocalDate,
        today: LocalDate
    ): LocalDate {
        val yearsBetween = ChronoUnit.YEARS.between(startDate, today)
        var tentativeEnd = startDate.plusYears(yearsBetween).minusDays(1)
        var n = yearsBetween
        if (tentativeEnd.isBefore(today)) {
            n += 1
        }
        return startDate.plusYears(n).minusDays(1)
    }

    private fun ceilDiv(a: Long, b: Long): Long {
        return (a + b - 1) / b
    }

    fun calculateEndByStartDate(startDateStr: String, daysToAdd: Long): String {
        return try {
            // 1. 定义日期格式
            val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")

            // 2. 解析输入日期
            val startDate = LocalDate.parse(startDateStr, formatter)

            // 3. 计算结束日期
            val endDate = startDate.plusDays(daysToAdd)

            // 4. 格式化输出
            endDate.format(formatter)
        } catch (e: DateTimeParseException) {
            // 处理无效日期格式
            ""
        } catch (e: Exception) {
            // 其他异常处理
            ""
        }
    }

    fun checkExpiration(endDateStr: String): Boolean {
        return try {
            val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
            val endDate = LocalDate.parse(endDateStr, formatter)
            val currentDate = LocalDate.now(ZoneId.systemDefault())
            currentDate.isAfter(endDate)
        } catch (e: Exception) {
            false // 处理解析异常
        }
    }

    fun calculateCyclePosition(startDateStr: String, endDateStr: String): Pair<Long, Long> {
         val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
        return try {
            // 解析日期
            val startDate = LocalDate.parse(startDateStr, formatter)
            val endDate = LocalDate.parse(endDateStr, formatter)
            val today = LocalDate.now()

            // 检查日期有效性
            if (today.isBefore(startDate) || today.isAfter(endDate)) {
                return Pair(-1, -1)
            }

            // 计算总天数差
            val totalDays = ChronoUnit.DAYS.between(startDate, today) + 1

            // 计算周期信息
            val cycleNumber = (totalDays - 1) / 7 + 1
            val dayInCycle = (totalDays - 1) % 7

            Pair(cycleNumber, dayInCycle)
        } catch (e: Exception) {
            Pair(-1, -1) // 处理格式错误或逻辑异常
        }
    }

    fun calculateGroupIndex(n: Int): Int {
        return when {
            n <= 6 -> 1
            else -> (n - 7) / 7 + 2 // 每7个数递增1
        }
    }

    fun getWeekDateRange(): Pair<Long, Long> {
        val calendar = Calendar.getInstance().apply {
            // 设置为本周日（假设周日为一周的第一天）
            set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)
            // 调整时间为当天的 00:00:00
            set(Calendar.HOUR_OF_DAY, 0)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }
        val startDate = calendar.timeInMillis

        // 计算下周六（周日 + 6天）的 23:59:59
        calendar.add(Calendar.DATE, 6)
        calendar.set(Calendar.HOUR_OF_DAY, 23)
        calendar.set(Calendar.MINUTE, 59)
        calendar.set(Calendar.SECOND, 59)
        val endDate = calendar.timeInMillis

        return Pair(startDate, endDate)
    }
    fun weekParseDate(dateStr: String): Long {
        return try {
            SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).parse(dateStr)?.time ?: 0L
        } catch (e: Exception) {
            0L
        }
    }

}